package com.arpa.wms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.cache.AreaCache;
import com.arpa.ntocc.common.common.cache.PartyCache;
import com.arpa.ntocc.common.common.cache.ShipmentCache;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.CommonUtil;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.domain.dto.ShipmentAuthorizationJsonBean;
import com.arpa.ntocc.common.domain.dto.WarehouseAuthorizationJsonBean;
import com.arpa.ntocc.common.domain.entity.UserLogin;
import com.arpa.ntocc.common.domain.enums.PartyTypeEnum;
import com.arpa.ntocc.common.domain.vo.TreeData;
import com.arpa.wms.cache.WarehouseCache;
import com.arpa.wms.cache.WarehouseShipmentCache;
import com.arpa.wms.cache.WarehouseSpaceCache;
import com.arpa.wms.domain.consts.NumConst;
import com.arpa.wms.domain.consts.PropertyConst;
import com.arpa.wms.domain.dto.InventoryDTO;
import com.arpa.wms.domain.dto.WarehouseDTO;
import com.arpa.wms.domain.entity.Location;
import com.arpa.wms.domain.entity.Warehouse;
import com.arpa.wms.domain.entity.WarehouseSpace;
import com.arpa.wms.domain.enums.DeleteFlagEnum;
import com.arpa.wms.domain.enums.StatusEnum;
import com.arpa.wms.domain.vo.WarehouseShipmentVO;
import com.arpa.wms.domain.vo.WarehouseSpaceVO;
import com.arpa.wms.domain.vo.WarehouseVO;
import com.arpa.wms.mapper.WarehouseMapper;
import com.arpa.wms.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.arpa.wms.domain.consts.CodeConst.WAREHOUSE_CODE;

/**
 * <p>
 * 仓库 服务实现类
 * </p>
 *
 * @author LEO
 * @since 2020-08-03
 */
@Service
public class WarehouseServiceImpl extends ServiceImpl<WarehouseMapper, Warehouse> implements IWarehouseService {



    private final IInventoryService iInventoryService;

    private final IWarehouseSpaceService iWarehouseSpaceService;

    private final ILocationService iLocationService;

    private final WarehouseCache warehouseCache;

    private final WarehouseSpaceCache warehouseSpaceCache;

    private final AreaCache areaCache;

    private final WarehouseShipmentCache warehouseShipmentCache;

    @Autowired
    private IWarehouseShipmentService warehouseShipmentService;

    private final PartyCache partyCache;

    @Resource
    private ShipmentCache shipmentCache;


    public WarehouseServiceImpl(WarehouseCache warehouseCache,
                                WarehouseSpaceCache warehouseSpaceCache,
                                IWarehouseSpaceService iWarehouseSpaceService,
                                ILocationService iLocationService,
                                AreaCache areaCache,
                                WarehouseShipmentCache warehouseShipmentCache,
                                PartyCache partyCache,
                                IInventoryService iInventoryService) {
        this.warehouseCache = warehouseCache;
        this.warehouseSpaceCache = warehouseSpaceCache;
        this.iWarehouseSpaceService = iWarehouseSpaceService;
        this.iLocationService = iLocationService;
        this.areaCache = areaCache;
        this.warehouseShipmentCache = warehouseShipmentCache;
        this.partyCache = partyCache;
        this.iInventoryService = iInventoryService;
    }

    /**
     * 保存
     *
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean save(Warehouse entity) {
        entity.setCode(IdUtil.simpleUUID());
        entity.setGroupCode(UserUtil.getBranchCode());
        entity.setCreatedBy(UserUtil.getCode());
        entity.setModifiedBy(UserUtil.getCode());
        entity.setCreatedName(partyCache.translate(UserUtil.getCode()));
        entity.setModifiedName(partyCache.translate(UserUtil.getCode()));

        List<String> areaList = entity.getAreaList();
        if (IterUtil.isNotEmpty(areaList) && areaList.size() == 4) {
            entity.setCountry(areaList.get(0));
            entity.setProvince(areaList.get(1));
            entity.setCity(areaList.get(2));
            entity.setCounty(areaList.get(3));
        }

        // 创建临时库区、库位
        initTempLocation(entity);

        warehouseCache.initAllCache();

        //清除仓库缓存
        warehouseCache.flushCacheAllByGroupCode(UserUtil.getBranchCode());

        return super.save(entity);
    }

    /**
     * 根据code更新实体
     *
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int updateByCode(Warehouse entity) {
        entity.setModifiedBy(UserUtil.getCode());
        entity.setModifiedName(partyCache.translate(UserUtil.getCode()));
        List<String> areaList = entity.getAreaList();
        if (IterUtil.isNotEmpty(areaList) && areaList.size() == 4) {
            entity.setCountry(areaList.get(0));
            entity.setProvince(areaList.get(1));
            entity.setCity(areaList.get(2));
            entity.setCounty(areaList.get(3));
        }


        warehouseCache.flushCache(entity.getCode());

        return baseMapper.update(entity, new QueryWrapper<Warehouse>().lambda().eq(Warehouse::getCode, entity.getCode()).eq(Warehouse::getGroupCode,UserUtil.getBranchCode()));
    }

    /**
     * 通过code获取仓库信息
     *
     * @param code
     * @return
     */
    @Override
    public Warehouse getByCode(String code) {
        Map<String, Object> temp = this.warehouseCache.get(code);
        if (MapUtil.isNotEmpty(temp)) {
            Warehouse entity = BeanUtil.mapToBean(temp, Warehouse.class, false);
            List<String> areaList = new ArrayList<>();
            areaList.add(entity.getCountry());
            areaList.add(entity.getProvince());
            areaList.add(entity.getCity());
            areaList.add(entity.getCounty());
            String areaStr = "";
            if (StrUtil.isNotBlank(entity.getProvince())) {
                if (StrUtil.isNotBlank(areaStr)) {
                    areaStr = areaStr + "/" + areaCache.translateProvince(entity.getProvince());
                } else {
                    areaStr = areaCache.translateProvince(entity.getProvince());
                }
            }
            if (StrUtil.isNotBlank(entity.getCity())) {
                if (StrUtil.isNotBlank(areaStr)) {
                    areaStr = areaStr + "/" + areaCache.translateCity(entity.getCity());
                } else {
                    areaStr = areaCache.translateCity(entity.getCity());
                }
            }
            if (StrUtil.isNotBlank(entity.getCounty())) {
                if (StrUtil.isNotBlank(areaStr)) {
                    areaStr = areaStr + "/" + areaCache.translateCounty(entity.getCounty());
                } else {
                    areaStr = areaCache.translateCounty(entity.getCounty());
                }
            }
            entity.setArea(areaStr);
            entity.setAreaList(areaList);
            return entity;
        }
        return null;
    }

    /**
     * 查询列表
     *
     * @param warehouseDTO
     * @return
     */
    @Override
    public List<WarehouseVO> queryList(WarehouseDTO warehouseDTO) {
        //排序字段名需要驼峰转数据库下划线类型字段名
        if (StringUtils.isNotEmpty(warehouseDTO.getSortField())) {
            warehouseDTO.setSortField(CommonUtil.camel2Underline(warehouseDTO.getSortField()));
        }
        return baseMapper.queryList(warehouseDTO);
    }

    /**
     * 查询合计,包含总数
     *
     * @param warehouseDTO
     * @return
     */
    @Override
    public WarehouseVO queryListSum(WarehouseDTO warehouseDTO) {
        WarehouseVO warehouseVO = baseMapper.queryListSum(warehouseDTO);
        return warehouseVO;
    }

    /**
     * 删除仓库
     *
     * @param codes
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result deleteByCode(List<String> codes) throws Exception {

        Map<String, Object> result = this.batchdel(codes);
        Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
        List<String> notDelete = MapUtil.get(result, "notDelete", List.class);
        List<String> InInventory = MapUtil.get(result, "inInventory", List.class);
        int failNum = codes.size() - success;
        StringBuilder info = new StringBuilder();
        info.append("删除成功" + success + "条；失败" + failNum + "条；");
        if (IterUtil.isNotEmpty(notDelete)) {
            for (String m : notDelete) {
                info.append("<br><font color='red'>仓库【" + m + "】删除失败，已被启用过;</font>");
            }
        }
        if (IterUtil.isNotEmpty(InInventory)) {
            for (String m : InInventory) {
                info.append("<br><font color='red'>仓库【" + m + "】删除失败，已被占用;</font>");
            }
        }
        return Result.ok(info.toString());

    }

    /**
     * 批量删除
     *
     * @param codes
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public Map<String, Object> batchdel(List<String> codes) {
        Map<String, Object> result = new HashMap<>();
        List<WarehouseVO> warehouses = queryByCodes(codes);
        Map<String, String> warehouseMap = warehouses.stream().collect(Collectors.toMap(WarehouseVO::getCode, WarehouseVO::getName));
        //不可删除code
        List<String> notDeleteCodes = warehouses.stream().filter(info -> info.getDeleteFlag().intValue() == DeleteFlagEnum.NOTDELETE.getCode().intValue()).map(info -> {
            return info.getCode();
        }).collect(Collectors.toList());
        List<String> notDeleteName = notDeleteCodes.stream().map(code -> {
            return warehouseMap.get(code);
        }).collect(Collectors.toList());
        result.put("notDelete", notDeleteName);
        List<String> tempCode = codes.stream().filter(code -> !notDeleteCodes.contains(code)).collect(Collectors.toList());
        List<String> tempNoDeleteCode = new ArrayList<>();
        List<String> inventorynotDeleteName = new ArrayList<>();
        tempCode.stream().forEach(code -> {
            InventoryDTO inventoryDTO = new InventoryDTO();
            inventoryDTO.setWarehouseCode(code);
            inventoryDTO.setGroupCode(UserUtil.getBranchCode());
            BigDecimal quantity = iInventoryService.queryInventorySum(inventoryDTO);
            if (quantity.compareTo(BigDecimal.ZERO) != 0) {
                tempNoDeleteCode.add(code);
                inventorynotDeleteName.add(warehouseMap.get(code));
            }
        });
        result.put("inInventory", inventorynotDeleteName);
        int num = 0;
        if (IterUtil.isNotEmpty(tempCode)) {
            List<String> deleteCodes = tempCode.stream().filter(code -> !tempNoDeleteCode.contains(code)).collect(Collectors.toList());
            if (IterUtil.isNotEmpty(deleteCodes)) {
                num = delete(deleteCodes);
            }
        }
        result.put(PropertyConst.SUCCESS, num);
        return result;
    }

    /**
     * 根据仓库code更新启用、停用状态
     *
     * @param codes
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int activeStatus(List<String> codes) {
        int num = this.changeStatus(codes, StatusEnum.ACTIVE, DeleteFlagEnum.NOTDELETE.getCode().toString());
        //仓库启用时，仓库中的临时库区和库位也要同时启用
        iWarehouseSpaceService.activeStatusByWarehouseCodes(codes);
        return num;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> unactiveStatus(List<String> codes) {
        Map<String, Object> result = new HashMap<>();
        Map<Boolean, List<Map<String, Object>>> warehouses = checkUse(codes);
        List<Map<String, Object>> notUse = warehouses.get(true);
        List<Map<String, Object>> use = warehouses.get(false);
        if (IterUtil.isNotEmpty(notUse)) {
            List<String> warehouseCodes = notUse.stream().map(r -> MapUtil.getStr(r, WAREHOUSE_CODE)).collect(Collectors.toList());
            if (IterUtil.isNotEmpty(warehouseCodes)) {
                this.changeStatus(warehouseCodes, StatusEnum.UNACTIVE, "");
                iWarehouseSpaceService.update(new UpdateWrapper<WarehouseSpace>().lambda().eq(WarehouseSpace::getGroupCode,UserUtil.getBranchCode())
                        .in(WarehouseSpace::getWarehouseCode, warehouseCodes)
                        .set(WarehouseSpace::getStatus, StatusEnum.UNACTIVE));
                iLocationService.update(new UpdateWrapper<Location>().lambda().in(Location::getWarehouseCode, warehouseCodes).eq(Location::getGroupCode,UserUtil.getBranchCode())
                        .set(Location::getStatus, StatusEnum.UNACTIVE));
                result.put(PropertyConst.SUCCESS, notUse.size());
            }
        }

        if (IterUtil.isNotEmpty(use)) {
            result.put("fail", use.size());

            List<String> message = use.stream().map(r ->
                    warehouseCache.translate(MapUtil.getStr(r, WAREHOUSE_CODE))).collect(Collectors.toList());
            result.put("msg", message);
        }
        return result;

    }


    /**
     * 校验仓库信息
     *
     * @param entity
     * @return
     */
    @Override
    public Result validateWarehouse(Warehouse entity) {
        // 校验必填项
        if (StrUtil.isBlank(entity.getName())) {
            return Result.error("仓库名称不能为空");
        }
        if (StrUtil.isBlank(entity.getSerialNumber())) {
            return Result.error("仓库编码不能为空");
        }
        if (StrUtil.isBlank(entity.getType())) {
            return Result.error("仓库类型不能为空");
        }
        // 校验仓库编码是否唯一, 同组织下不能有相同的仓库编码
        List<Warehouse> warehouses = this.list(new LambdaQueryWrapper<Warehouse>()
                .eq(Warehouse::getSerialNumber, entity.getSerialNumber())
                .eq(Warehouse::getGroupCode, UserUtil.getBranchCode()));
        // 将自身过滤掉
        warehouses = warehouses.stream().filter(e -> !e.getCode().equals(entity.getCode())).collect(Collectors.toList());
        if (!warehouses.isEmpty()) {
            return Result.error("存在相同的仓库编码，请确认后重新操作。");
        }

        return Result.ok();
    }


    /**
     * 变更仓库状态
     *
     * @param codes  标识
     * @param active 状态
     * @return
     */
    private int
    changeStatus(List<String> codes, StatusEnum active, String deleteFlag) {
        for (String code : codes) {
            this.warehouseCache.flushCache(code);
        }
        String codesStr = codes.stream().map(c -> StrUtil.wrap(c, "'")).collect(Collectors.joining(","));
        return this.baseMapper.changeStatus(codesStr, active.getValue(), deleteFlag,UserUtil.getBranchCode());
    }

    /**
     * 前台页面仓库下拉数据
     * 查询当前登录用户所属机构下启用，并开启库位管理的仓库
     *
     * @return
     */
    @Override
    public List<WarehouseVO> findWarehouse() {
        //获取所有库区
        List<Map<String, Object>> allWarehouseSpace = warehouseSpaceCache.getAllByGroupCode(UserUtil.getBranchCode());
        List<Map<String, Object>> allWarehouse = this.warehouseCache.getAllByGroupCode(UserUtil.getBranchCode());
        String groupCode = UserUtil.getBranchCode();
        List<WarehouseVO> warehouseVOS = allWarehouse.stream()
                .map(m -> BeanUtil.mapToBean(m, WarehouseVO.class, false))
                .filter(w -> StrUtil.equals(w.getStatus(), StatusEnum.ACTIVE.getValue()) && w.getLocationManagement() == 1 && StrUtil.equals(w.getGroupCode(), UserUtil.getBranchCode()))
                .peek(r -> {
                    List<Map<String, Object>> warehouseShipments = warehouseShipmentCache.get(r.getCode());
                    if (IterUtil.isNotEmpty(warehouseShipments)) {
                        List<WarehouseShipmentVO> warehouseShipmentVOS = warehouseShipments.stream()
                                .map(s -> BeanUtil.mapToBean(s, WarehouseShipmentVO.class, false)).collect(Collectors.toList());
                        r.setShipmentVOList(warehouseShipmentVOS);
                    }

                    // 获取非临时库区的库区列表
                    List<WarehouseSpaceVO> warehouseSpaceVOS = allWarehouseSpace.stream()
                            .filter(ws -> StrUtil.equals(MapUtil.getStr(ws, WAREHOUSE_CODE), r.getCode()) && StrUtil.equals(MapUtil.getStr(ws, "tempSpace"), "0"))
                            .map(m -> BeanUtil.mapToBean(m, WarehouseSpaceVO.class, false)).collect(Collectors.toList());
                    r.setWarehouseSpaceVOS(warehouseSpaceVOS);
                })
                .collect(Collectors.toList());
        return warehouseVOS;
    }

    @Override
    public List<WarehouseVO> findAllWarehouse() {
        String groupCode = UserUtil.getBranchCode();
        List<WarehouseVO> warehouses = this.warehouseCache.getAllByGroupCode(groupCode).stream()
                    .map(m -> BeanUtil.mapToBean(m, WarehouseVO.class, false)).collect(Collectors.toList());
        if (IterUtil.isNotEmpty(warehouses)) {
            warehouses = warehouses.stream().filter(w -> StrUtil.equals(w.getStatus(),
                    StatusEnum.ACTIVE.getValue()) &&
                    w.getLocationManagement() == 1 &&
                    StrUtil.equals(w.getGroupCode(), groupCode)).collect(Collectors.toList());
        }

        return warehouses;
    }

    /**
     * 检查仓库使用情况
     *
     * @param code
     */
    public Map<Boolean, List<Map<String, Object>>> checkUse(List<String> code) {
        //获取所有仓库库存
        List<Map<String, Object>> quantity = iInventoryService.getQuantity(code);
        Map<Boolean, List<Map<String, Object>>> warehouseQuantity = quantity.stream().collect(Collectors.groupingBy(r -> MapUtil.getInt(r, "quantity") == 0));
        return warehouseQuantity;

    }

    /**
     * 初始化临时库区、库位
     *
     * @param warehouse
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public Result initTempLocation(Warehouse warehouse) {
        WarehouseSpace space = iWarehouseSpaceService.createTempSpace(warehouse.getCode());
        iLocationService.createTempLocation(space);
        return Result.ok();
    }

    /**
     * 验证“启用库位管理”状态
     * 如果启用库位管理设为关闭，则需要检查该仓库下是否还有库存
     *
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result closeLocationManagement(Warehouse entity) {
        // 查询数据库，如果是刚改为关闭，则继续
        Warehouse dbEntity = this.getOne(new QueryWrapper<Warehouse>().lambda().eq(Warehouse::getCode, entity.getCode()).eq(Warehouse::getGroupCode,UserUtil.getBranchCode()));
        if (NumConst.NUM_ZERO.equals(dbEntity.getLocationManagement())) {
            // 如果数据库中原本就是“关闭”状态，则视为已关闭，不用再继续之后的操作
            return Result.ok();
        }
        // 查询该仓库下是否有库存
        if (iInventoryService.warehouseHasInv(entity.getCode())) {
            throw new ServiceException("该仓库下有库存，无法关闭“启用库位管理”");
        }

        // 关闭该仓库下的库区、库位
        iWarehouseSpaceService.update(new UpdateWrapper<WarehouseSpace>().lambda().eq(WarehouseSpace::getWarehouseCode, entity.getCode())
                .eq(WarehouseSpace::getGroupCode,UserUtil.getBranchCode())
                .eq(WarehouseSpace::getTempSpace, 0)
                .set(WarehouseSpace::getStatus, StatusEnum.UNACTIVE.getValue()));
        iLocationService.update(new UpdateWrapper<Location>().lambda().eq(Location::getWarehouseCode, entity.getCode())
                .eq(Location::getGroupCode,UserUtil.getBranchCode())
                .eq(Location::getTempLocation, 0)
                .set(Location::getStatus, StatusEnum.UNACTIVE.getValue()));

        return Result.ok();
    }

    /**
     * @description oms获取所有仓库信息
     * oms端可以看到库位管理状态为未启用的仓库，wms不可以
     * @author xuyang
     * @date 2020/12/14 9:29
     **/
    @Override
    public List<WarehouseVO> findOmsWarehouse() {
        String groupCode = UserUtil.getBranchCode();
        //获取所有库区
        List<Map<String, Object>> allWarehouseSpace = warehouseSpaceCache.getAllByGroupCode(groupCode);
        List<Map<String, Object>> allWarehouse = this.warehouseCache.getAllByGroupCode(groupCode);
        List<WarehouseVO> warehouseVOS = allWarehouse.stream()
                .map(m -> BeanUtil.mapToBean(m, WarehouseVO.class, false))
                .filter(w -> StrUtil.equals(w.getStatus(), StatusEnum.ACTIVE.getValue()) &&
                        StrUtil.equals(w.getGroupCode(), groupCode))
                .map(r -> {
                    List<Map<String, Object>> warehouseShipments = warehouseShipmentCache.get(r.getCode());
                    if (IterUtil.isNotEmpty(warehouseShipments)) {
                        List<WarehouseShipmentVO> warehouseShipmentVOS = warehouseShipments.stream()
                                .map(s -> BeanUtil.mapToBean(s, WarehouseShipmentVO.class, false))
                                .collect(Collectors.toList());
                        r.setShipmentVOList(warehouseShipmentVOS);
                    }

                    // 获取非临时库区的库区列表
                    List<WarehouseSpaceVO> warehouseSpaceVOS = allWarehouseSpace.stream()
                            .filter(ws -> StrUtil.equals(MapUtil.getStr(ws, WAREHOUSE_CODE), r.getCode()) &&
                                    StrUtil.equals(MapUtil.getStr(ws, "tempSpace"), "0"))
                            .map(m -> BeanUtil.mapToBean(m, WarehouseSpaceVO.class, false))
                            .collect(Collectors.toList());
                    r.setWarehouseSpaceVOS(warehouseSpaceVOS);
                    return r;
                })
                .collect(Collectors.toList());
        return warehouseVOS;
    }

    @Override
    public List<WarehouseVO> queryByCodes(List<String> codes) {

        return baseMapper.getByCodes(codes,UserUtil.getBranchCode());
    }


    private int delete(List<String> list) {
        int num = 0;
        if (IterUtil.isNotEmpty(list)) {
            for (String code : list) {
                boolean flag = this.update(new UpdateWrapper<Warehouse>().lambda().eq(Warehouse::getCode, code).eq(Warehouse::getGroupCode,UserUtil.getBranchCode())
                        .set(Warehouse::getDeleted, 1));
                if (flag) {
                    num++;
                    this.warehouseCache.flushCache(code);
                    // 同步删除该仓库下的库区、库位
                    iWarehouseSpaceService.remove(new UpdateWrapper<WarehouseSpace>().lambda()
                            .eq(WarehouseSpace::getWarehouseCode, code).eq(WarehouseSpace::getGroupCode,UserUtil.getBranchCode()));
                    iLocationService.remove(new UpdateWrapper<Location>().lambda().eq(Location::getWarehouseCode, code).eq(Location::getGroupCode,UserUtil.getBranchCode()));
                    // 清除缓存
                    this.warehouseSpaceCache.flushCacheByGroupCode(UserUtil.getBranchCode());
                    //TODO 清除库位缓存
                    //this.locationCache.flushCacheByGroupCode();
                }
            }
        }
        return num;
    }


    @Override
    public List<TreeData> cascadeData(String userLoginType) {
        PartyTypeEnum partyTypeEnum = UserUtil.getPartyType();
        if(partyTypeEnum == PartyTypeEnum.SUPER_ADMIN || partyTypeEnum== PartyTypeEnum.PLAT_ADMIN) {
            //获取机构所有启用仓库的绑定信息
            List<WarehouseShipmentVO> warehouseShipmentVOS = warehouseShipmentService.getAll(UserUtil.getBranchCode());
            if (StrUtil.equals(UserLogin.USER_LOGIN_TYPE_WAREHOUSE, userLoginType)) {
                //仓库授权，所有启用库位管理的仓库
                //根据仓库分组货主
                Map<String, List<WarehouseShipmentVO>> warehouseShipmentVOSMap = warehouseShipmentVOS.stream()
                        .filter(w -> w.getLocationManagement() == 1)
                        .collect(Collectors.groupingBy(k -> k.getWarehouseCode() + "#" + k.getWarehouseName()));
                return warehouseShipmentVOSMap.entrySet().parallelStream().map(entry -> {
                    TreeData treeDataVO = new TreeData();
                    String[] k = StrUtil.split(entry.getKey(), "#");
                    treeDataVO.setValue(k[0]);
                    treeDataVO.setLabel(k[1]);
                    treeDataVO.setSpread(true);
                    List<TreeData> children = entry.getValue().stream()
                            .map(m -> {
                                TreeData treeData1 = new TreeData();
                                treeData1.setValue(m.getShipmentCode());
                                treeData1.setLabel(m.getShipmentName());
                                treeData1.setSpread(true);
                                return treeData1;
                            }).collect(Collectors.toList());
                    if (IterUtil.isNotEmpty(children)) {
                        treeDataVO.setChildren(children);
                    }
                    return treeDataVO;

                }).collect(Collectors.toList());
            }

            if (StrUtil.equals(UserLogin.USER_LOGIN_TYPE_SHIPMENT, userLoginType)) {

                //过滤所有启用OMS的货主并且仓库启用并按货主分组
                Map<String, List<WarehouseShipmentVO>> warehouseShipmentVOSMap = warehouseShipmentVOS.stream()
                        .filter(r -> r.getUseOms() == 1)
                        .collect(Collectors.groupingBy(k -> k.getShipmentCode() + "#" + k.getShipmentName()));
                return warehouseShipmentVOSMap.entrySet().parallelStream().map(m -> {
                    TreeData treeDataVO = new TreeData();
                    String[] k = StrUtil.split(m.getKey(), "#");
                    treeDataVO.setValue(k[0]);
                    treeDataVO.setLabel(k[1]);
                    treeDataVO.setSpread(true);
                    List<TreeData> children = m.getValue().stream()
                            .map(w -> {
                                TreeData treeData1 = new TreeData();
                                treeData1.setValue(w.getWarehouseCode());
                                treeData1.setLabel(w.getWarehouseName());
                                treeData1.setSpread(true);
                                return treeData1;
                            }).collect(Collectors.toList());
                    if (IterUtil.isNotEmpty(children)) {
                        treeDataVO.setChildren(children);
                    }
                    return treeDataVO;
                }).collect(Collectors.toList());
            }

        }else{
            if (StrUtil.equals(UserLogin.USER_LOGIN_TYPE_WAREHOUSE, userLoginType)) {
                List<WarehouseAuthorizationJsonBean> warehouseAuthorizationJsonBeans = UserUtil.getAuthorizeWarehouses();
                if(IterUtil.isEmpty(warehouseAuthorizationJsonBeans)){
                    return new ArrayList<>();
                }
                return warehouseAuthorizationJsonBeans.parallelStream().map(m -> {
                    TreeData treeDataVO = new TreeData();
                    treeDataVO.setValue(m.getWarehouse());
                    treeDataVO.setLabel(warehouseCache.translate(m.getWarehouse()));
                    treeDataVO.setSpread(true);
                    List<TreeData> children = m.getShipment().stream().filter(r->warehouseShipmentService.isBind(m.getWarehouse(),r))
                            .map(w -> {
                                TreeData treeData1 = new TreeData();
                                treeData1.setValue(w);
                                treeData1.setLabel(shipmentCache.translate(w));
                                treeData1.setSpread(true);
                                return treeData1;
                            }).collect(Collectors.toList());
                    if (IterUtil.isNotEmpty(children)) {
                        treeDataVO.setChildren(children);
                    }
                    return treeDataVO;
                }).collect(Collectors.toList());
            }
            if (StrUtil.equals(UserLogin.USER_LOGIN_TYPE_SHIPMENT, userLoginType)) {
                List<ShipmentAuthorizationJsonBean> shipmentAuthorizationJsonBeans = UserUtil.getAuthorizeShipments();
                if(IterUtil.isEmpty(shipmentAuthorizationJsonBeans)){
                    return new ArrayList<>();
                }
                return shipmentAuthorizationJsonBeans.parallelStream().map(m -> {
                    TreeData treeDataVO = new TreeData();
                    treeDataVO.setValue(m.getShipment());
                    treeDataVO.setLabel(shipmentCache.translate(m.getShipment()));
                    treeDataVO.setSpread(true);
                    List<TreeData> children = m.getWarehouse().stream()
                            .map(w -> {
                                TreeData treeData1 = new TreeData();
                                treeData1.setValue(w);
                                treeData1.setLabel(warehouseCache.translate(w));
                                treeData1.setSpread(true);
                                return treeData1;
                            }).collect(Collectors.toList());
                    if (IterUtil.isNotEmpty(children)) {
                        treeDataVO.setChildren(children);
                    }
                    return treeDataVO;
                }).collect(Collectors.toList());
            }
        }

        return new ArrayList<>();
    }

    /**
     * 查询列表不分页
     * @param warehouseDTO
     * @return
     */
    @Override
    public List<WarehouseVO> queryWarehouseList(WarehouseDTO warehouseDTO) {
        return baseMapper.queryWarehouseList(warehouseDTO);
    }
}
